package com.mz.ozy.activity.shop;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mz.ozy.R;
import com.mz.ozy.activity.shop.db.DbDao;
import com.mz.ozy.adapter.CustomTagAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.HotSearchBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.HotSearchPresenter;
import com.mz.ozy.mvp.view.HotSearchContract;
import com.mz.ozy.widget.flowlayout.FlowLayout;
import com.mz.ozy.widget.flowlayout.TagFlowLayout;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends BaseActivity<HotSearchContract.View, HotSearchPresenter> implements HotSearchContract.View, TextView.OnEditorActionListener {

    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_search_btn)
    TextView tvSearchBtn;

    @BindView(R.id.flowTagLayout1)
    TagFlowLayout mFlowTagLayout1;
    @BindView(R.id.flowTagLayout2)
    TagFlowLayout mFlowTagLayout2;
    @BindView(R.id.flowTagLayout3)
    TagFlowLayout mFlowTagLayout3;
    @BindView(R.id.iv_search_clear)
    ImageView mIvSearchClear;
    @BindView(R.id.ll_histroy_search)
    LinearLayout mLlHistroySearch;
    private CustomTagAdapter mSearchTagAdapter;
    private CustomTagAdapter mSearchTagAdapter1;
    private CustomTagAdapter mSearchTagAdapter2;
    private List<String> mList = new ArrayList<>();
    private List<String> mList1 = new ArrayList<>();
    private List<String> mList2 = new ArrayList<>();
    private StringBuffer sb = new StringBuffer();

    private DbDao mDbDao;
    private boolean isSearch = false;

    @Subscribe
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        etSearch.setOnEditorActionListener(this);    //搜索键盘
        mDbDao = new DbDao(this);
        mSearchTagAdapter = new CustomTagAdapter(this, mFlowTagLayout1, mList);
        mFlowTagLayout1.setAdapter(mSearchTagAdapter);
        mFlowTagLayout1.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Intent intent = new Intent(SearchActivity.this, SortSearchActivity.class);
                intent.putExtra("type", "1");
                intent.putExtra("content", mList.get(position));
                startActivity(intent);
                return false;
            }
        });
        final List<String> searchList = mDbDao.queryData("");
        mSearchTagAdapter.refresh(searchList, 10);
        if (searchList.size() == 0) {
            mLlHistroySearch.setVisibility(View.GONE);
        } else {
            mLlHistroySearch.setVisibility(View.VISIBLE);
        }

        mSearchTagAdapter1 = new CustomTagAdapter(this, mFlowTagLayout2, mList1);
        mFlowTagLayout2.setAdapter(mSearchTagAdapter1);
        mFlowTagLayout2.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doSearch(mList1.get(position));
                return false;
            }
        });

        mSearchTagAdapter2 = new CustomTagAdapter(this, mFlowTagLayout3, mList2);
        mFlowTagLayout3.setAdapter(mSearchTagAdapter2);
        mFlowTagLayout3.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                doSearch(mList2.get(position));
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!TextUtils.isEmpty(etSearch.getText().toString().trim())) {
                    isSearch = true;
                    tvSearchBtn.setText("搜索");
                } else {
                    isSearch = false;
                    tvSearchBtn.setText("取消");
                }
            }
        });
        mPresenter.onHotSearch(this);
    }

    @Override
    public void onHotSearchSuccess(HotSearchBean searchBean) {
        if (searchBean != null) {
            mList1.clear();
            mList2.clear();
            if (searchBean.getListHot() != null) {
                for (int i = 0; i < searchBean.getListHot().size(); i++) {
                    mList1.add(searchBean.getListHot().get(i).getWord());
                }
                mSearchTagAdapter1.notifyDataChanged();
            }
            if (searchBean.getList() != null) {
                for (int i = 0; i < searchBean.getList().size(); i++) {
                    mList2.add(searchBean.getList().get(i).getWord());
                }
                mSearchTagAdapter2.notifyDataChanged();
            }
        }
    }

    @OnClick({R.id.ll_search_btn, R.id.iv_search_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_search_btn: {
                if (isSearch) {
                    doSearch(etSearch.getText().toString().trim());
                } else {
                    finish();
                }
                break;
            }
            case R.id.iv_search_clear:      //清空历史搜索
                onClearHistroySearchDialog();
                break;
        }
    }

    private void doSearch(String searchKey) {
//        final String searchContent = etSearch.getText().toString().trim();
//        if (TextUtils.isEmpty(searchContent)) {
//            ToastUtils.showToast("搜索内容不能为空");
//            return;
//        }
//        finish();
//        Intent intent = new Intent(this, SortSearchActivity.class);
//        intent.putExtra("content", searchContent);
//        intent.putExtra("type", 0 + "");
//        startActivity(intent);


        //欧花商城搜素
        if (0 == getIntent().getIntExtra("ob_shop", 1)) {
            EventBus.getDefault().post(new EventBean(Constants.EventCode.OB_SERACH_BACK, searchKey));
            finish();
            return;
        }

//            sb.append(mEtSearchContent.getText().toString().trim()).append(",");
//            SharePreferencesData.addSharePreferencesData(SearchActivity.this, "key", sb.toString().substring(0, sb.toString().length() - 1));

        if (searchKey.length() != 0) {
            mLlHistroySearch.setVisibility(View.VISIBLE);
            boolean hasData = mDbDao.hasData(searchKey);
            if (!hasData) {
                mDbDao.insertData(searchKey);
            } else {
//                Toast.makeText(SearchActivity.this, "该内容已在历史记录中", Toast.LENGTH_SHORT).show();
            }
            mSearchTagAdapter.refresh(mDbDao.queryData(""), 10);
            etSearch.setText("");
            Intent intent = new Intent(SearchActivity.this, SortSearchActivity.class);
            intent.putExtra("type", "1");
            intent.putExtra("content", searchKey);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(SearchActivity.this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
        }
    }

    //弹框的电话号码待确认，这个号码显示的应该是对应商家的电话
    private void onClearHistroySearchDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_clear_histroy_search, null);
        Button btnCancel = view.findViewById(R.id.btn_cancel);
        Button btnOk = view.findViewById(R.id.btn_ok);
        final Dialog dialog = new Dialog(this, R.style.custom_dialog);
        dialog.setContentView(view);
        dialog.show();
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDbDao.deleteData();
                mSearchTagAdapter.refresh(mDbDao.queryData(""), 10);
                mLlHistroySearch.setVisibility(View.GONE);
                dialog.dismiss();

            }
        });

        /**
         * 设置宽度全屏，要设置在show的后面
         */
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams layoutParams = dialogWindow.getAttributes();
        //layoutParams.gravity=Gravity.BOTTOM;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
        dialogWindow.setAttributes(layoutParams);
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 当按了搜索之后关闭软键盘
            ((InputMethodManager) etSearch.getContext().getSystemService(
                    Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    SearchActivity.this.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);

            doSearch(etSearch.getText().toString().trim());
            return true;
        }
        return false;
    }

}
